package edu.del.springbootredisbusinesspractice.web.controller;

import edu.del.springbootredisbusinesspractice.pojo.Product;
import edu.del.springbootredisbusinesspractice.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController()
@RequestMapping("/api")
public class ProductController {

    @Autowired
    private ProductService productService;

    // 查询全部商品信息
    @GetMapping("/products")
    public List<Product> getAllProducts() {
        return productService.list();
    }

    // 查询单个商品信息
    @GetMapping("/product/{id}")
    public Product getProductById(@PathVariable(value = "id") Integer id) {
        return productService.getProductById(id);
    }

    // 修改商品信息
    @PutMapping("/product/{id}")
    public ResponseEntity<?> updateProduct(@PathVariable Integer id, @RequestBody Product product) {
        product.setId(Long.valueOf(id)); // 确保 ID 一致
        int result = productService.updateProduct(product);
        if (result > 0) {
            return ResponseEntity.ok("商品更新成功");
        } else {
            return ResponseEntity.badRequest().body("商品更新失败");
        }
    }
}
